<template>
  <el-dialog v-el-drag-dialog :title="!form.dbKey?'新建数据源':'编辑数据源'" :visible.sync="visible" :append-to-body="appendToBody" :before-close="onClose">
    <el-form ref="dbForm" :model="form" :rules="rules" label-width="120px" :disabled="!hasLoaded">
      <el-card>
        <el-form-item label="数据标识" prop="dbKey">
          <el-input v-model="form.dbKey" :readonly="readonly" />
        </el-form-item>
        <el-form-item label="数据库名称" prop="dbName">
          <el-input v-model="form.dbName" />
        </el-form-item>
        <el-form-item label="url" prop="url">
          <el-input v-model="form.url" />
        </el-form-item>
        <el-form-item label="驱动名称" prop="driverClassName">
          <el-select v-model="form.driverClassName">
            <el-option
              v-for="item in optionOfDriverClass"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option
              v-for="item in optionOfStatus"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-card>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button v-if="hasLoaded" type="primary" icon="el-icon-check" @click="onSubmit">确 定</el-button>
      <el-button icon="el-icon-close" @click="onClose">关 闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { dbaseLoad, dbaseSave } from '@/api/tool/dbase'

export default {
  name: 'DbFormDialog',
  data() {
    const validateUniq = (rule, value, callback) => {
      if (value === undefined || value === '') {
        rule.message = '该项不能为空'
        return callback(new Error(rule.message))
      }

      const param = rule.param.replaceParam
      if (this.form.dbKey && param === 'dbKey') {
        return callback()
      }
      rule.param[param] = value
      rule.param.dbKey = this.form.dbKey
      this.$http.get(rule.url, {
        params: rule.param
      }).then(response => {
        if (response.valid) {
          callback()
        } else {
          callback(new Error(rule.message))
        }
      }).catch(() => {
        callback()
      })
    }

    return {
      visible: false,
      readonly: false,
      appendToBody: false,
      hasLoaded: false,
      form: {
        dbKey: undefined,
        dbName: undefined,
        url: undefined,
        driverClassName: undefined,
        username: undefined,
        password: undefined,
        status: undefined
      },
      rules: {
        dbKey: [{
          required: true,
          trigger: 'blur',
          param: {
            replaceParam: 'dbKey'
          },
          validator: validateUniq,
          url: `${process.env.VUE_APP_MODULE_ADMIN_API}/api/system/dbase/checkDbUnique`,
          message: '已存在数据标识'
        }],
        dbName: [{
          required: true,
          trigger: 'blur',
          param: {
            replaceParam: 'dbName'
          },
          validator: validateUniq,
          url: `${process.env.VUE_APP_MODULE_ADMIN_API}/api/system/dbase/checkDbUnique`,
          message: '已存在数据库名称'
        }],
        url: [
          { required: true, message: '数据库url不能为空' }
        ]
      },
      optionOfDriverClass: [],
      optionOfStatus: []
    }
  },
  methods: {
    init(dbKey) {
      this.hasLoaded = false
      this.form.dbKey = dbKey || null
      this.visible = true
      this.$nextTick(() => {
        this.loadForm(dbKey)
        this.getDictData()
      })
    },
    loadForm(dbKey) {
      if (dbKey) {
        this.readonly = true
        dbaseLoad({ 'id': dbKey }).then(response => {
          this.form = this.$api.objectUpdate(this.form, response.param)
        }).catch(() => {})
      }

      // 判断当前用户权限
      this.hasLoaded = this.$perm.hasPermissionOr(['tool:db:edit'])
    },
    getDictData() {
      const that = this
      this.$http.all([this.$dictGroup('sys_available_type'), this.$dictGroup('sys_driver_class_name')])
      .then(this.$http.spread(function (status, driverClass) {
        that.optionOfStatus = status
        that.optionOfDriverClass = driverClass
      }))
    },
    onSubmit() {
      this.$refs.dbForm.validate(valid => {
        if (valid) {
          dbaseSave(this.form).then(response => {
            this.$modal.msgSuccess(response.msg)
            this.$emit('confirmForm')
            this.onClose()
          }).catch(() => {})
        }
      })
    },
    onClose() {
      this.$refs.dbForm.resetFields()
      this.visible = false
      this.readonly = false
    }
  }
}
</script>
